/**
 * Copyright (C),2007-2016, LonBon Technologies Co. Ltd. All Rights Reserved.
 */

package com.dwxt.cdms.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 *
 * @author:xl
 * @Description: RSA加密解密入口
 * @Date: 15 :29  2017/12/11.
 * @Modified begin by xl
 * ----@Date: 10:30 2018/1/9
 * ----@Description:logger
 * @Modified end
 */
@Slf4j
public class RsaUtil {

    private static Logger logger = LoggerFactory.getLogger(RsaUtil.class);

    public static final Integer KEY_TYPE_LOGIN = 1;

    public static final Integer KEY_TYPE_TOKEN = 2;

    public static final String KEY_TYPE_LOGIN_DIR = "/loginkeys";

    public static final String KEY_TYPE_TOKEN_DIR = "/tokenkeys";

    public static String encode(String message,Integer keyType)  {
        // TODO 文件存在性校验
        String messageEncode = null;
        try {
            // 加载私钥文件地址
            String classFilePath = null;
            /*if (KEY_TYPE_TOKEN.equals(keyType)){
                classFilePath = ResourcePathUtil.getConfigPathByCommand()+KEY_TYPE_TOKEN_DIR;
            }*/
            // 本地测试
            classFilePath = "/home/lb/work/NBZS/ny_server_locationcare/src/main/resources/loginkeys";
            String publicKeyStr = RsaEncrypt.loadPublicKeyByFile(classFilePath);
            RSAPublicKey publicKey = RsaEncrypt.loadPublicKeyByStr(publicKeyStr);
            // 公钥加密
            byte[] res = RsaEncrypt.encrypt(publicKey,message.getBytes("utf-8"));
            // base64编码
            byte[] decodeBase64 = Base64.encodeBase64(res);
            if(null == decodeBase64){
                return null;
            }
            messageEncode = new String(decodeBase64,"utf-8");
        }catch (Exception ex){
            logger.error("RSAUtil.encode error" + ex.getMessage());
        }
        return messageEncode;
    }

    public static String decode(String encodeStr,Integer keyType){
        // TODO 文件存在性校验
//        logger.error(encodeStr);
        String passwordDecode = null;
        String classFilePath = null;
        String privateKeyStr = null;
        try {
            // 加载私钥文件地址
//            if (KEY_TYPE_LOGIN.equals(keyType)){
//                classFilePath = ResourcePathUtil.getConfigPathByCommand()+KEY_TYPE_LOGIN_DIR;
//            }else if(KEY_TYPE_TOKEN.equals(keyType)){
//                classFilePath = ResourcePathUtil.getConfigPathByCommand()+KEY_TYPE_TOKEN_DIR;
//            }else{
//                return null;
//            }
            // 本地测试
           classFilePath = "/home/lb/fsdownload/tokenkeys";
//            logger.error(classFilePath);
            privateKeyStr = RsaEncrypt.loadPrivateKeyByFile(classFilePath);
            RSAPrivateKey privateKey = RsaEncrypt.loadPrivateKeyByStr(privateKeyStr);
            // base64解码
            byte[] decodeBase64 = Base64.decodeBase64(encodeStr);
            // 私钥解密
            byte[] res = RsaEncrypt.decrypt(privateKey,decodeBase64);
            passwordDecode = new String(res,"utf-8");
        }catch (Exception ex){
            log.error("RSAUtil.decode error" + ex.getMessage()
            +" ; token: "+encodeStr+" ; key path: "+classFilePath+" ; privateKeyStr: "+privateKeyStr);
        }
        return passwordDecode;
    }

    public static void main(String[] args) {
      //  String password = "Gz9weqrzkXwPgPnpeD5GJMFs9HiHt4EryBbk4hAtZEgKBdFwgmk8WcEwHDBDSNFAJrFYOlXaizhs7t/SM4qPC+aBlF7BSsy8ZNCaPrWvuzcd8Fs+lcB/PLGUuvgIS8QqTYzsYjyfUQNjEK/FeyN/G15peD4nxTwvoqGAozwbSh1thFq16n6x3a5QBplwVsrG5BsD8YW+INYKV27JpkBTBVZvxDknypDDOt5SIpx6x+++VCwIowral99Upl2lqhQZ5ygCRAN6/gQ+wBrcq9W6bQG947H0VyWG2zAVAXwEpUsYz2lGt4VBUAwBXJEN1d86H4OlY01E9r8wC4Y4uQx1yA==";
        String password1 = "aChuxNAtife9e6PUbBdHp87ht+lh76cSJ28WPfH+F8nb3j0ZunEezTfoz3zbiHgQFGhA73iKBbcTZkfaGplHlXV9zOr7HkxQ7szf8H9u6o2WcPErzP86Pg+F3P4ohPZDU7SwIVKjw787m3nx2bHXFHU0A4lL8V6ux7yK4Wvye+Q=";
        //String res = decode(password1,KEY_TYPE_LOGIN);

//        String token = "{\"id\":\"6e3ed29c-f435-11e8-8eb2-f2801f1b9fd1\",\"name\":\"ABDCAF6BD8BFD74D515083AD87269463\",\"pwd\":\"ABDCAF6BD8BFD74D515083AD87269463\",\"t\":42568026232,\"tp\":100}";
//        String pass = "123456";
//        pass = MD5Util.MD5EncodeUtf8(pass);
//        pass = MD5Util.MD5EncodeUtf8(pass+"nb_lbhf");
//
//        System.out.println(pass);
//        String a = encode(pass,KEY_TYPE_LOGIN);
//        System.out.println(a);
//        String b = decode(a,KEY_TYPE_TOKEN);
//        System.out.println(b);

         String a="GzUjF7X+89mlNl0nskM37YcBsBjYEmPyTV5RqecyO5+15C/J5UeoCEf7nwNkRwt+JePQH5WYdN8U5yc6U/BR/8tygmemF05VaHwqu7zp6pjKPRD07ydQPkWf9DB2xAEn5U6zGAbvSVuV2Xt++JBPXP1KcSQVLzIm0jI15N+UopH3gbAa7RSKhOEP0vgQ/Tk4GVghXmAccA6WNyRlKcj3HEvWlX9cgyDmYRJ/ue5VO7fFheeXZWN0LP15lvbTVcr3Ozz3QeaBG8bk864G4/J0Nvb+uVLl0fsCF/6JS1riB559y+wsX3KlFgpv6C0LkuvPmkoMh9HJWi/352f0cycvDgMlQffNgalt9q4xlNrMFOCbxDhxZiEpGVomYHM53VQ4ggEMfJEyXyUAqEZd5piGe86x04EEin0mUkikpFE9qnLviZ69prWxv8q4Os7SuDWaitn6HVt9DkA/gPvXvAMhATnIuc931Ua01h1f/4PXziBeN1noRhKwTisX6IGtk58Ig+oVXRZjxPoXIzNlmEHVjvVEQALNGeLAAvz6Dz1jv6P4bYRA8NBs9cUeBfu3rhO2Vv+eX3wwqSXkK1LsJiAANJyAvUshM0I7+bTsCTev/Gh2085b1sffh9TZTdKgvtM1u/jxue0xwM/lL0mJ7eV/PCSpsFWVtnIrBU1WCi6UObE=";

        String  c = decode(a,KEY_TYPE_LOGIN);
        System.out.println(c);
        //TokenVerify.start();

//        String  d = decode(password,KEY_TYPE_LOGIN);
//        System.out.println(d);
    }

}
